package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.mapper.PatrolMapper;
import com.woniu.mapper.SpaceMapper;
import com.woniu.pojo.*;
import com.woniu.mapper.RoadMapper;
import com.woniu.service.IRoadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.vo.RoadQueryReturnVo;
import com.woniu.vo.RoadQueryVo;
import com.woniu.vo.RoadVo;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lqg
 * @since 2022-10-12
 */
@Service
public class RoadServiceImpl extends ServiceImpl<RoadMapper, Road> implements IRoadService {

    @Resource
    private RoadMapper roadMapper;

    @Resource
    private SpaceMapper spaceMapper;

    @Resource
    private PatrolMapper patrolMapper;

    /**
     * 分页条件查询
     * @param currentPage    当前页
     * @param pageSize       每页数据量
     * @param roadQueryVo    路段查询vo
     * @return               分页查询数据
     */
    @Override
    public IPage<RoadQueryReturnVo> search(Integer currentPage, Integer pageSize, RoadQueryVo roadQueryVo) {
        // 0. 空值检测
        if (currentPage == null || currentPage < 1) {
            // 若currentPage 传入空值或小于一则令其等于1
            currentPage = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 5;
        }


        // 1. 创建分页
        IPage<Road> page = new Page<>(currentPage, pageSize);

        // 2. 创建wrapper
        QueryWrapper<Road> wrapper = new QueryWrapper<>();
        QueryWrapper<Road> last = new QueryWrapper<>();
        // 3. 检测查询条件
        if (roadQueryVo != null) {
            if (roadQueryVo.getName() != null && roadQueryVo.getName().length() > 0) {
                // 路段名存在 wrapper添加路段名
                wrapper.like("name", roadQueryVo.getName());
            }

            if (roadQueryVo.getType() != null && roadQueryVo.getType().length() > 0) {
                // 路段类型存在 wrapper添加路段类型
                wrapper.eq("type", roadQueryVo.getType());
            }

            List<Road> roads = roadMapper.selectList(wrapper);

            if (roads == null) {
                return null;
            }
            List<Long> roadId1 = new ArrayList<>();
            for (int i = 0; i < roads.size(); i++) {
                roadId1.add(roads.get(i).getId());
            }

            if (roadQueryVo.getPatrolName() != null && roadQueryVo.getPatrolName().length() > 0) {
                // 根据巡检员姓名查询巡检员id
                List<Long> patrolIdList = roadMapper.selectPatrolIdsByPatrolName(roadQueryVo.getPatrolName());
                QueryWrapper<Road> patrolName = new QueryWrapper<>();
                // 建立路段id的list
                List<Long> roadIdList = new ArrayList<>();
                // 对patrolIdList迭代 根据巡检员id查询路段id
                for (Long patrolId : patrolIdList) {
                    List<Long> roadIds = roadMapper.selectRoadIdsByPatrolId(patrolId);
                    // 将roadIds元素添加到roadIdList
                    roadIdList.addAll(roadIds);
                }

                if (roadIdList.size() > 0) {
                    // 将查询出来的路段id 添加到 wrapper中 查询
                    for (Long roadId : roadIdList) {
                        patrolName.eq("id", roadId).or();
                    }
                } else {
                    return null;
                }
                List<Road> roads1 = roadMapper.selectList(patrolName);

                if (roads1 == null) {
                    return null;
                }

                List<Long> roadId2 = new ArrayList<>();
                for (int i = 0; i < roads1.size(); i++) {
                    roadId2.add(roads1.get(i).getId());
                }
                // 对roads  与roads1集合 取交集
                roadId1.retainAll(roadId2);
                if (roadId1.size() > 0) {
                    for (Long id : roadId1) {
                        System.out.println(id+ "======================================");
                        last.eq("id", id).or();
                    }
                } else {
                    return null;
                }

            } else {
                last = wrapper;
            }
        }

        IPage<Road> roadIPage = roadMapper.selectPage(page, last);
        System.out.println("========================");
        // 将roadIPage 里的数据封装到 retrunList中
        List<Road> roadList = roadIPage.getRecords();
        List<RoadQueryReturnVo> roadReturn = new ArrayList<>();
        IPage<RoadQueryReturnVo> roadReturnPage = new Page<>();
        roadReturnPage.setTotal(roadIPage.getTotal());
        roadReturnPage.setPages(roadIPage.getPages());
        roadReturnPage.setCurrent(roadIPage.getCurrent());
        roadReturnPage.setSize(roadIPage.getSize());

        for (Road road : roadList) {
            RoadQueryReturnVo returnVo = new RoadQueryReturnVo();
            returnVo.setId(road.getId());
            returnVo.setArea(road.getArea());
            returnVo.setName(road.getName());
            returnVo.setLimitedSpaceNum(road.getLimitedSpaceNum());
            returnVo.setType(road.getType());
            returnVo.setCreateTime(road.getCreateTime());

            // 查询泊位数量的wrapper
            QueryWrapper<Space> countWrapper = new QueryWrapper<>();
            countWrapper.eq("road_id", road.getId());
            Long spaceCount = spaceMapper.selectCount(countWrapper);
            returnVo.setSpaceCount(spaceCount);

            // 查询巡检员
            List<String> patrolNameList = roadMapper.selectPatrolsNameByRoadId(road.getId());
            String patrolNames = null;
            for (int i = 0; i < patrolNameList.size(); i++) {
                if (i == 0) {
                    patrolNames = patrolNameList.get(i);
                } else {
                    patrolNames = patrolNames + " / " + patrolNameList.get(i);
                }
            }
            returnVo.setPatrolNames(patrolNames);
            // 查询运维员
            List<String> maintainerNameList = roadMapper.selectMaintainersNameByRoadId(road.getId());
            String maintainerNames = null;
            for (int i = 0; i < maintainerNameList.size(); i++) {
                if (i == 0) {
                    maintainerNames = maintainerNameList.get(i);
                } else {
                    maintainerNames = maintainerNames + " / " + maintainerNameList.get(i);
                }
            }
            returnVo.setMaintainerNames(maintainerNames);

            roadReturn.add(returnVo);
        }
        roadReturnPage.setRecords(roadReturn);


        return roadReturnPage;
    }

    @Override
    public boolean edit(RoadVo roadVo) {
        Road road = new Road();
        road.setId(roadVo.getId());
        road.setName(roadVo.getName());
        road.setArea(roadVo.getArea());
        road.setType(roadVo.getType());
        road.setLimitedSpaceNum(roadVo.getLimitedSpaceNum());
        roadMapper.updateById(road);

        // 添加关联关系
        List<Long> patrolIdList = roadVo.getPatrolIdList();
        for (Long patrolId : patrolIdList) {
            RoadPatrol roadPatrol = new RoadPatrol();
            roadPatrol.setRoadId(road.getId());
            roadPatrol.setPatrolId(patrolId);
            roadMapper.insertPatrolAndRoad(roadPatrol);
        }

        List<Long> maintainerIdList = roadVo.getMaintainerIdList();
        for (Long maintainerId : maintainerIdList) {
            RoadMaintainer roadMaintainer = new RoadMaintainer();
            roadMaintainer.setRoadId(road.getId());
            roadMaintainer.setMaintainerId(maintainerId);
            roadMapper.insertMaintainerAndRoad(roadMaintainer);
        }


        return true;
    }

    @Override
    public RoadQueryReturnVo searchById(Long id) {
        Road road = roadMapper.selectById(id);
        RoadQueryReturnVo returnVo = new RoadQueryReturnVo();
        returnVo.setId(road.getId());
        returnVo.setName(road.getName());
        returnVo.setType(road.getType());
        returnVo.setLimitedSpaceNum(road.getLimitedSpaceNum());
        returnVo.setArea(road.getArea());
        returnVo.setCreateTime(road.getCreateTime());

        // 查询泊位数量的wrapper
        QueryWrapper<Space> countWrapper = new QueryWrapper<>();
        countWrapper.eq("road_id", road.getId());
        Long spaceCount = spaceMapper.selectCount(countWrapper);
        returnVo.setSpaceCount(spaceCount);

        // 查询巡检员
        List<Long> patrolIdList = roadMapper.selectPatrolsByRoadId(road.getId());
        returnVo.setPatrolIdList(patrolIdList);

        // 查询运维员
        List<Long> maintainerIdList = roadMapper.selectMaintainersByRoadId(road.getId());
        returnVo.setMaintainerIdList(maintainerIdList);

        return returnVo;
    }

    @Override
    public boolean add(RoadVo roadVo) {
        Road road = new Road();
        road.setName(roadVo.getName());
        road.setArea(roadVo.getArea());
        road.setType(roadVo.getType());
        road.setLimitedSpaceNum(roadVo.getLimitedSpaceNum());
        roadMapper.insert(road);
        // 添加关联关系
        List<Long> patrolIdList = roadVo.getPatrolIdList();
        for (Long patrolId : patrolIdList) {
            RoadPatrol roadPatrol = new RoadPatrol();
            roadPatrol.setRoadId(road.getId());
            roadPatrol.setPatrolId(patrolId);
            roadMapper.insertPatrolAndRoad(roadPatrol);
        }

        List<Long> maintainerIdList = roadVo.getMaintainerIdList();
        for (Long maintainerId : maintainerIdList) {
            RoadMaintainer roadMaintainer = new RoadMaintainer();
            roadMaintainer.setRoadId(road.getId());
            roadMaintainer.setMaintainerId(maintainerId);
            roadMapper.insertMaintainerAndRoad(roadMaintainer);
        }


        return true;
    }


}
